/*
 * @Descripttion: 
 * @version: 
 * @Author: chenbolin@msn.cn
 * @Date: 2022-09-02 14:48:52
 * @LastEditors: chenbolin@msn.cn
 * @LastEditTime: 2023-10-12 18:46:03
 */
#include "HalADC.h"
#include "adc.h"
#include "HalCtype.h"

#define HAL_ADC_DATA_COUNT 5

static uint16_t g_adcBuff[HAL_ADC_DATA_COUNT][HAL_ADC_CHANNEL_COUNT];

uint16_t HalADCRealValue(uint8_t ch)
{
    return g_adcBuff[0][ch];
}

uint16_t HalADCGetChannelValue(uint8_t ch)
{
    uint16_t max = 0, min = 0xffff;
    uint8_t i;
    uint32_t sum = 0;
    uint16_t average;

    HAL_ADC_Stop_DMA(&hadc1);

    for (i = 0; i < HAL_ADC_DATA_COUNT; i++)
    {
        if (g_adcBuff[i][ch] > max)
        {
            max = g_adcBuff[i][ch];
        }

        if (g_adcBuff[i][ch] < min)
        {
            min = g_adcBuff[i][ch];
        }
        sum += g_adcBuff[i][ch];
    }
    average = (uint16_t)((sum - max - min) / (HAL_ADC_DATA_COUNT - 2));
    HAL_ADC_Start_DMA(&hadc1, (uint32_t *)g_adcBuff, HAL_ADC_CHANNEL_COUNT * HAL_ADC_DATA_COUNT);
    return average;
}

void HalADCInitialize(void)
{
//    HAL_ADCEx_Calibration_Start(&hadc1);
    HAL_ADC_Start_DMA(&hadc1, (uint32_t *)g_adcBuff, HAL_ADC_CHANNEL_COUNT * HAL_ADC_DATA_COUNT);
}
